package com.ruite.livepad.service;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

import com.ruite.livepad.R;
import com.ruite.livepad.util.HttpDownListener;
import com.ruite.livepad.util.OkHttpDownUtil;
import com.zero.cdownload.CDownload;
import com.zero.cdownload.listener.CDownloadListener;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

import okhttp3.Call;
import okhttp3.Response;


/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions and extra parameters.
 */
public class DownloadIntentService extends Service {

    public static final String ACTION_VIDEO = "com.ruite.livepad.service.action.FOO";
    public static final String ACTION_MUSIC = "com.ruite.livepad.service.action.BAZ";

    // TODO: Rename parameters
    public static final String EXTRA_URL = "com.ruite.livepad.service.extra.EXTRA_URL";
    public static final String EXTRA_FILENAME = "com.ruite.livepad.service.extra.EXTRA_FILENAME";
    public static final String EXTRA_NOTIFICATIONID = "com.ruite.livepad.service.extra.NOTIFICATIONID";

    //handler状态
    public static final int DOWN_SUCCESS = 1;
    public static final int DOWN_LOADING = 2;
    public static final int DOWN_ERROR = 3;
    public static final int DOWN_START = 4;
    private static final String CHANNEL_ID = "ander_dorwloadapk_notification";
    //通知
    private NotificationManager notificationManager;
    private Notification notification; //下载通知进度提示
    private NotificationCompat.Builder builder;

    private long totalSize;// 文件总大小
    private long downloadCount = 0;// 已经下载好的大小

    private Handler handler;
    private int NotificationID = 1;
    private String localFilePath;
    private boolean start = false;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case DOWN_START:
                        notification = builder.build();
                        notificationManager.notify(NotificationID, notification);
                        Toast.makeText(DownloadIntentService.this, "开始下载", Toast.LENGTH_SHORT).show();
                        break;
                    case DOWN_SUCCESS:
                        // 震动提示
                        Toast.makeText(DownloadIntentService.this, "下载完成,文件保存在" + localFilePath, Toast.LENGTH_LONG).show();
                        break;
                    case DOWN_LOADING:
                        builder.setProgress((int) totalSize, (int) downloadCount, false);
                        builder.setContentText("当前已下载" + getPercent(downloadCount, totalSize));
                        notification = builder.build();
                        notificationManager.notify(NotificationID, notification);
                        break;
                    case DOWN_ERROR:
                        builder.setAutoCancel(true);
                        notificationManager.cancel(NotificationID);
                        Toast.makeText(DownloadIntentService.this, "下载出错", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            createNotificationChannel(notificationManager);
        }
        builder = getNotificationBuilder();
        if (intent != null) {
            final String action = intent.getAction();
            final String url = intent.getStringExtra(EXTRA_URL);
            final String fileName = intent.getStringExtra(EXTRA_FILENAME);
//            NotificationID = intent.getIntExtra(EXTRA_NOTIFICATIONID, 100);
            NotificationID = 100;
            Log.e("DownloadIntentService", "NotificationIDNotificationIDNotificationID------------------>" + NotificationID);
            if (ACTION_VIDEO.equals(action)) {
                handleActionDownloadVideo(url, fileName);
            } else if (ACTION_MUSIC.equals(action)) {
                handleActionDownloadMusic(url, fileName);
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionDownloadVideo(String url, final String fileName) {
//        start = true;
//        OkHttpDownUtil okHttpDownUtil = new OkHttpDownUtil();
//        handler.sendEmptyMessage(DOWN_START);
//
//        okHttpDownUtil.getRenewalDownRequest(url, new File(fileName), new HttpDownListener() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                start = false;
//                handler.sendEmptyMessage(DOWN_ERROR);
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e2) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onResponse(Call call, Response response, long mTotalLength, long mAlreadyDownLength) {
//                totalSize = mTotalLength;
//                downloadCount = mAlreadyDownLength;
//                if (mAlreadyDownLength == mTotalLength) {
//                    start = false;
//                    Log.e("HongLi", "onComplete localFilePath:" + fileName);
//                    localFilePath = fileName;
//                    try {
//                        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//                        vibrator.vibrate(500L);// 参数是震动时间(long类型)
//                    } catch (Exception e) {
//
//                    }
//                    builder.setContentText("下载完成");
//                    builder.setAutoCancel(true);
//                    notificationManager.notify(NotificationID, builder.build());
////                notificationManager.cancel(NotificationID);
//                    handler.sendEmptyMessage(DOWN_SUCCESS);
//                }
//            }
//        });
////
        CDownload.getInstance().create(url, new CDownloadListener() {
            @Override
            public void onPreStart() {
                Log.e("HongLi", "onPreStart");
                start = true;
                handler.sendEmptyMessage(DOWN_START);
                new Thread() {
                    @Override
                    public void run() {
                        while (start) {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            handler.sendEmptyMessage(DOWN_LOADING);
                        }
                    }
                }.start();

            }

            @Override
            public void onProgress(long maxSIze, long currentSize) {
                Log.e("HongLi", "in onProgress maxSIze:" + maxSIze + ";currentSize:" + currentSize);
                totalSize = maxSIze;
                downloadCount = currentSize;
            }

            @Override
            public void onComplete(String localFilePath) {
                start = false;
                Log.e("HongLi", "onComplete localFilePath:" + fileName);
                File file = new File(localFilePath);
                file.renameTo(new File(fileName));
                DownloadIntentService.this.localFilePath = fileName;
                try {
                    Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                    vibrator.vibrate(500L);// 参数是震动时间(long类型)
                } catch (Exception e) {

                }
                builder.setContentText("下载完成");
                builder.setAutoCancel(true);
                notificationManager.notify(NotificationID, builder.build());
            }

            @Override
            public void onError(String errorMessage) {
                start = false;
                handler.sendEmptyMessage(DOWN_ERROR);
            }

            @Override
            public void onCancel() {
                start = false;
                Log.e("HongLi", "onCancel");
                handler.sendEmptyMessage(DOWN_ERROR);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        CDownload.getInstance().start(url);
    }

    /**
     * Handle action Baz in the provided background thread with the provided
     * parameters.
     */
    private void handleActionDownloadMusic(String url, final String fileName) {
        CDownload.getInstance().create(url, new CDownloadListener() {
            @Override
            public void onPreStart() {
                start = true;
                Log.e("HongLi", "onPreStart");
                handler.sendEmptyMessage(DOWN_START);
                new Thread() {
                    @Override
                    public void run() {
                        while (start) {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            handler.sendEmptyMessage(DOWN_LOADING);
                        }
                    }
                }.start();
            }

            @Override
            public void onProgress(long maxSIze, long currentSize) {
                Log.e("HongLi", "in onProgress maxSIze:" + maxSIze + ";currentSize:" + currentSize);
                totalSize = maxSIze;
                downloadCount = currentSize;
            }

            @Override
            public void onComplete(String localFilePath) {
                start = false;
                Log.e("HongLi", "onComplete localFilePath:" + localFilePath);
                File file = new File(localFilePath);
                file.renameTo(new File(fileName));
                DownloadIntentService.this.localFilePath = fileName;
                handler.sendEmptyMessage(DOWN_SUCCESS);
            }

            @Override
            public void onError(String errorMessage) {
                start = false;
                Toast.makeText(DownloadIntentService.this, "下载失败！" + errorMessage, Toast.LENGTH_SHORT).show();
                handler.sendEmptyMessage(DOWN_ERROR);
            }

            @Override
            public void onCancel() {
                start = false;
                Log.e("HongLi", "onCancel");
                handler.sendEmptyMessage(DOWN_ERROR);
            }
        });
        CDownload.getInstance().start(url);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel(NotificationManager notificationManager) {
        // 通知渠道
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                "ander drowload apk default channel.", NotificationManager.IMPORTANCE_HIGH);
        //是否绕过请勿打扰模式
        channel.canBypassDnd();
        // 开启指示灯，如果设备有的话。
        channel.enableLights(true);
        // 开启震动
        channel.enableVibration(false);
        //是否会有灯光
        channel.shouldShowLights();
        //获取系统通知响铃声音的配置
        channel.getAudioAttributes();
        channel.setImportance(NotificationManager.IMPORTANCE_LOW);
        //  设置指示灯颜色
        channel.setLightColor(Color.RED);
        // 设置是否应在锁定屏幕上显示此频道的通知
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        // 设置是否显示角标
        channel.setShowBadge(true);
        //  设置绕过免打扰模式
        channel.setBypassDnd(true);
        // 设置震动频率
        //最后在notificationmanager中创建该通知渠道
        notificationManager.createNotificationChannel(channel);
    }

    public NotificationCompat.Builder getNotificationBuilder() {
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setWhen(System.currentTimeMillis())
                .setContentTitle("下载") //设置通知标题
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) //设置通知的大图标
                //修改小圆圈默认背景颜色
                .setColor(getResources().getColor(R.color.colorAccent))
                .setDefaults(Notification.DEFAULT_LIGHTS) //设置通知的提醒方式： 呼吸灯
                .setPriority(NotificationCompat.PRIORITY_DEFAULT) //设置通知的优先级：最大
                .setAutoCancel(false)//设置通知被点击一次是否自动取消
                .setContentText("当前下载" + "0%")
                .setProgress(100, 0, false);
    }

    private String getPercent(long x, long total) {
        String result = "";// 接受百分比的值
        double x_double = x * 1.0;
        double tempresult = x_double / total;
        // 百分比格式，后面不足2位的用0补齐 ##.00%
        DecimalFormat df1 = new DecimalFormat("0.0%");
        result = df1.format(tempresult);
        return result;
    }
}
